

(function($) {
	
	$.widget("ui.form", $.extend({ } ,$.ui.mouse, {
		
		options: { 
			// initial values are stored in the widget's prototype 
			url: "_procesa.php",
			isAjax: true,
			submitButton: "submit",
			msgContainer: "elformerror",
			msgItemTagOpen: "<p>",
			msgItemTagClose: "</p>",
			preloaderHtml: "loading..",
			controls: [],
			refreshOnComplete: true
		},
		
		_init: function() {
		
			this._setData('errors', []);
			this._setData('values', []);
			
			$("#"+this.options.msgContainer).hide();
			
			var myself = "#"+this.element.attr('id');
			
			$("#"+this.options.submitButton).bind("click", function(evt,data) { 
				$(myself).form("process");
		    });
			
			// ADD EVENT HANDLERS
			var len = this.options.controls.length;
			for(var i=0; i<len; i++) {
				var itemId = this.options.controls[i].id;
				
				$('#'+itemId).bind("onValidationErrors", function(evt,data) { 
					$(myself).form("addErrors", data);
			    });
				
				$('#'+itemId).bind("onGetValue", function(evt,data) { 
					$(myself).form("addValue", {name:$(evt.currentTarget).attr('id'), value:data});
			    });				
			}			
			//
			
		},
		
		addErrors: function(controlErrors) {
			var errors = this._getData('errors');
			var len = controlErrors.length;
			for(var j=0; j<len; j++) {
				errors.push(controlErrors[j]);
			}			
			this._setData('errors', errors);				
		},
		
		addValue: function(valueObj) {
			var values = this._getData('values');
			values.push(valueObj);
			this._setData('values', values);
		},		
		
		validateFields: function() {
		
			// CHECK EACH VALIDATION REGEX
			var len = this.options.controls.length;
			for(var i=0; i<len; i++) {
				var itemId = this.options.controls[i].id;
				var itemKind = this.options.controls[i].kind;
				//$('#'+itemId).textbox("validate");
				to_eval = "$('#" + itemId + "')." + itemKind + "('validate');";
				eval(to_eval);
			}

		},		
		
		getValues: function() {
			
			// CHECK EACH VALIDATION REGEX
			var len = this.options.controls.length;
			for(var i=0; i<len; i++) {
				var itemId = this.options.controls[i].id;
				var itemKind = this.options.controls[i].kind;
				//$('#'+itemId).textbox("getValue");
				to_eval = "$('#" + itemId + "')." + itemKind + "('getValue');";
				eval(to_eval);				
			}

		},			
		
		disableControls: function() {
			// DESABILITO TODOS LOS CONTROLES
			var len = this.options.controls.length;
			for(var i=0; i<len; i++) {
				var itemId = this.options.controls[i].id;
				var itemKind = this.options.controls[i].kind;
				//$('#'+itemId).textbox("disable");
				to_eval = "$('#" + itemId + "')." + itemKind + "('disable');";
				eval(to_eval);				
			}			
			//
		},	
		
		enableControls: function() {
			// DESABILITO TODOS LOS CONTROLES
			var len = this.options.controls.length;
			for(var i=0; i<len; i++) {
				var itemId = this.options.controls[i].id;
				var itemKind = this.options.controls[i].kind;
				//$('#'+itemId).textbox("enable");
				to_eval = "$('#" + itemId + "')." + itemKind + "('enable');";
				eval(to_eval);				
			}			
			//
		},		
		
		refreshControls: function() {
			// DESABILITO TODOS LOS CONTROLES
			var len = this.options.controls.length;
			for(var i=0; i<len; i++) {
				var itemId = this.options.controls[i].id;
				var itemKind = this.options.controls[i].kind;
				//$('#'+itemId).textbox("refresh");
				to_eval = "$('#" + itemId + "')." + itemKind + "('refresh');";
				eval(to_eval);				
			}			
			//
		},			
		
		process: function() {
			var myself = "#"+this.element.attr('id');
			this.validateFields();
			var errors = this._getData('errors');
			this._setData('errors', []);
			this._setData('values', []);
			
			var errorMsg = "";
			
			$(this.options.submitButton).hide();
			
			// CHECK ERRORS
			var len = errors.length;
			for(var i=0; i<len; i++) {
				errorMsg += this.options.msgItemTagOpen + errors[i] + this.options.msgItemTagClose;
			}
			
			if (len == 0) errorMsg = false;
			
			$("#"+this.options.msgContainer).slideUp('fast', function() {
				$(myself).form("msgRestart", errorMsg);
			});
			
			
		},
		
		msgRestart: function(errorMsg) {
			var submitButtonId = this.options.submitButton;
			
			if (errorMsg !== false){ // MUESTRO LOS ERRORES
				$("#"+this.options.msgContainer).html(errorMsg);
				$("#"+this.options.msgContainer).slideDown('fast', function() {
					$(submitButtonId).show();
				});				
			}
			else { // NO HAY ERRORES, ENVÍO LA DATA
				this.prepareToSend();
			}
		},	
		
		prepareToSend: function() {
			var myself = "#"+this.element.attr('id');
			
			this.disableControls();
			
			$("#"+this.options.msgContainer).html(this.options.preloaderHtml);
			$("#"+this.options.msgContainer).slideDown('fast', function() {
				$(myself).form("sendData");
			});		

		},
		
		sendData: function() {
			// GET EACH VALUE
			this.getValues();
			
			var values = this._getData('values');
			var data = {};
			
			// CREO EL OBJETO QUE VOY A USAR PARA POSTEAR 
			var len = values.length;
			for(var i=0; i<len; i++) {
				var item = values[i];
				data[item.name] = item.value;
			}			
			
			// TEST PARA VER SI TIENE TODA LA DATA QUE ESPERO
			/*
			debugObj = "";
			for(var prop in data) {
			    //if(data.hasOwnProperty(prop))
			    	debugObj += "&" + prop + "=" + data[prop];
			}
			alert(debugObj);
			*/
			//

			var myself = "#"+this.element.attr('id');
			
			$.ajax({
					url: this.options.url,
					global: false,
					type: "POST",
					data: data,
					dataType: "json",
					success: function(serverResponse){
						 
						$(myself).form("prepareToEnd", serverResponse);
			         
					}
			   }
			);			
			
			
		},			
				
		
		prepareToEnd: function(serverResponse) {
			var myself = "#"+this.element.attr('id');
			$("#"+this.options.msgContainer).slideUp('fast', function() {
				$(myself).form("end", serverResponse);
			});		

		},
		

		end: function(serverResponse) {
			
			$(this.options.submitButton).show();
			this.enableControls();
			
			/*
			debugObj = "";
			for(var prop in serverResponse.data) {
			    //if(data.hasOwnProperty(prop))
			    	debugObj += "<br>" + prop + "=" + serverResponse.data[prop];
			}	
			*/		
			
			if (serverResponse.success !== false){ // NO HAY ERRORES
				if (this.options.refreshOnComplete == true){
					this.refreshControls();
				}
				
				$("#"+this.options.msgContainer).html(serverResponse.msg);
				$("#"+this.options.msgContainer).slideDown('fast', function() {
				    // Animation complete.
				});				
			}
			else { // HAY ERRORES
					
				var errorMsg = "";
				
				for(var prop in serverResponse.validationErrors) {
					var itemId = serverResponse.validationErrors[prop].id;
					var itemErrors = serverResponse.validationErrors[prop].errors;
					
					var len = itemErrors.length;
					for(var i=0; i<len; i++) {
						errorMsg += this.options.msgItemTagOpen + itemErrors[i] + this.options.msgItemTagClose;
					}						
					$('#'+itemId).textbox("externalError"); // FUERZO EL ERROR EN CADA ITEM PARA QUE CAMBIE DE ESTADO
				}					
				
				if (errorMsg == "") errorMsg = false;
				this.msgRestart(errorMsg);
				
			}
		}
		

	
		
		
		

	}));

	
})(jQuery);


